import { Component, AfterViewInit, ViewChild } from '@angular/core';
import { NavController, NavParams, InfiniteScroll, Refresher, Content, Img } from 'ionic-angular';
import { Park } from '../../providers/park-data/park';
import { ParkDataProvider } from '../../providers/park-data/park-data';
import { updateImgs } from 'ionic-angular/components/content/content';
import { ParkDetailPage } from '../park-detail/park-detail';


@Component({
  selector: 'page-park-list',
  templateUrl: 'park-list.html',
})
export class ParkListPage implements AfterViewInit {
  //使用注解@ViewChild方式访问Content
  @ViewChild(Content) _content: Content;  

  parks: Park[] = [];

  private num: number = 10; //每页显示记录
  private curPage: number = 1; //当前页数
  private hasMore: boolean = true; //是否有更多数据
  isSearch: boolean;

  constructor(
    public navCtrl: NavController, 
    public navParams: NavParams,
    public parkDataProvider: ParkDataProvider) {
  }

  ionViewDidLoad() {
    this.getPark(this.num,this.curPage);
  }


  /**
   * 分页获取景区信息
   * @param num 
   * @param page 
   */
  getPark(num: number, page: number): void{
    this.parkDataProvider.getParks(num,page).subscribe(parks=>{
      //this.parks = parks;
      //保留原有数据
      if(parks.length > 0){ 
        //存在更多数据时保留原有数据并增加数据
        this.parks = this.parks.concat(parks);
      }
      else{
        //当没有更多的数据时，hasMore设置为假
        this.hasMore = false;
      }
    });
  }



  /**
   * 向下滚动加载更多数据
   * @param infiniteScroll 
   */
  doInfinite(infiniteScroll: InfiniteScroll):void{
    if(!this.hasMore){
      infiniteScroll.complete();
      return;
    }

    setTimeout(()=>{
      this.curPage += 1;
      this.getPark(this.num,this.curPage);
      infiniteScroll.complete();
    },500);
  }


  /**
   * 下拉数据刷新
   * @param refresher 
   */
  doRefresh(refresher: Refresher):void{
    setTimeout(()=>{
      this.curPage =1;
      this.getPark(this.num,this.curPage);
      refresher.complete();
    },1000);
  }

  
  itemTapped(park: Park): void{
    //使用导航控件
    this.navCtrl.push(ParkDetailPage,{park: park});

  }

  /**
   * 搜索
   * @param event 
   */
  searchParks(event:any){
 
  }


  /**
   * 重新显示结果集
   * @param event 
   */
  resetParks(event:any){
    this.curPage = 1;
    this.isSearch = false;
    this.parks = [];
    this.getPark(this.num,this.curPage);
  }

  ngAfterViewInit(): void {
    //修补在Virtual-Scroll中图片显示的问题
    if(this._content){
      this._content.imgsUpdate = ()=>{
        if(
            this._content._scroll.initialized && 
            this._content._imgs.length &&
            this._content.isImgsUpdatable()){
              this._content._imgs.forEach((img: Img)=>{img._rect = null});
              updateImgs(
                this._content._imgs,
                this._content._cTop * -1,
                this._content.contentHeight,
                this._content.directionY,1400,400
              );
        }
      };
    }
    
  }
   

}
